import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { useTranslation } from 'react-i18next'
import {
  CubeIcon,
  PlusIcon,
  MagnifyingGlassIcon,
  EllipsisVerticalIcon,
  PencilIcon,
  ChartBarIcon,
  EyeIcon,
  ArrowDownTrayIcon,
  StarIcon
} from '@heroicons/react/24/outline'
import { AppDispatch } from '@/store'
import { fetchMyPlugins, selectMyPlugins, selectPluginsLoading } from '@/store/slices/pluginSlice'
import { Card, Button, Input, StatusBadge, LoadingSkeleton, ConfirmModal } from '@/components/ui'
import { ErrorBoundary } from '@/components/common'

export const MyPluginsPage: React.FC = () => {
  const { t } = useTranslation()
  const dispatch = useDispatch<AppDispatch>()
  const myPlugins = useSelector(selectMyPlugins)
  const isLoading = useSelector(selectPluginsLoading)

  // Local state
  const [searchTerm, setSearchTerm] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('all')
  const [deleteModalOpen, setDeleteModalOpen] = useState(false)
  const [pluginToDelete, setPluginToDelete] = useState<string | null>(null)

  useEffect(() => {
    dispatch(fetchMyPlugins())
  }, [dispatch])

  // Filter plugins based on search and status
  const filteredPlugins = myPlugins.filter(plugin => {
    const matchesSearch = plugin.displayName.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         plugin.description?.toLowerCase().includes(searchTerm.toLowerCase())
    const matchesStatus = statusFilter === 'all' || plugin.status === statusFilter
    return matchesSearch && matchesStatus
  })

  // const handleDeletePlugin = (pluginId: string) => {
  //   setPluginToDelete(pluginId)
  //   setDeleteModalOpen(true)
  // }

  const confirmDelete = async () => {
    if (pluginToDelete) {
      // TODO: Implement delete plugin action
      console.log('Deleting plugin:', pluginToDelete)
      setDeleteModalOpen(false)
      setPluginToDelete(null)
    }
  }

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="flex justify-between items-center">
          <LoadingSkeleton width="200px" height="32px" />
          <LoadingSkeleton width="120px" height="40px" />
        </div>
        <Card className="p-6">
          <LoadingSkeleton lines={5} />
        </Card>
      </div>
    )
  }

  return (
    <ErrorBoundary>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">{t('plugins.title')}</h1>
            <p className="text-gray-600 mt-1">
              {t('plugins.subtitle')}
            </p>
          </div>
          <Button as={Link} to="/developer/plugins/new" icon={<PlusIcon />}>
            {t('plugins.createNew')}
          </Button>
        </div>

        {/* Filters */}
        <Card className="p-6">
          <div className="flex flex-col sm:flex-row gap-4">
            <div className="flex-1">
              <Input
                placeholder={t('marketplace.searchPlaceholder')}
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                leftIcon={<MagnifyingGlassIcon />}
              />
            </div>
            <div className="sm:w-48">
              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                className="form-select w-full"
              >
                <option value="all">{t('plugins.filters.allStatus')}</option>
                <option value="pending">{t('plugins.status.pending')}</option>
                <option value="approved">{t('plugins.status.approved')}</option>
                <option value="rejected">{t('plugins.status.rejected')}</option>
                <option value="suspended">{t('plugins.status.suspended')}</option>
              </select>
            </div>
          </div>
        </Card>

        {/* Plugins Grid */}
        {filteredPlugins.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredPlugins.map((plugin) => (
              <Card key={plugin.id} className="p-6 hover:shadow-lg transition-shadow">
                <div className="flex justify-between items-start mb-4">
                  <div className="flex-1">
                    <h3 className="text-lg font-semibold text-gray-900 mb-1">
                      {plugin.displayName}
                    </h3>
                    <StatusBadge status={plugin.status || 'pending'} />
                  </div>
                  <div className="relative">
                    <button className="p-1 text-gray-400 hover:text-gray-600">
                      <EllipsisVerticalIcon className="h-5 w-5" />
                    </button>
                  </div>
                </div>

                <p className="text-gray-600 text-sm mb-4 line-clamp-2">
                  {plugin.description || t('plugins.noDescription')}
                </p>

                <div className="flex items-center justify-between text-sm text-gray-500 mb-4">
                  <div className="flex items-center">
                    <ArrowDownTrayIcon className="h-4 w-4 mr-1" />
                    {plugin.totalDownloads.toLocaleString()}
                  </div>
                  <div className="flex items-center">
                    <StarIcon className="h-4 w-4 mr-1 text-yellow-400" />
                    {plugin.rating.average.toFixed(1)}
                  </div>
                </div>

                <div className="flex gap-2">
                  <Button
                    as={Link}
                    to={`/developer/plugins/${plugin.id}`}
                    variant="outline"
                    size="sm"
                    icon={<EyeIcon />}
                    className="flex-1"
                  >
                    {t('common.view')}
                  </Button>
                  <Button
                    as={Link}
                    to={`/developer/plugins/${plugin.id}/edit`}
                    variant="outline"
                    size="sm"
                    icon={<PencilIcon />}
                    className="flex-1"
                  >
                    {t('common.edit')}
                  </Button>
                  <Button
                    as={Link}
                    to={`/developer/plugins/${plugin.id}/analytics`}
                    variant="outline"
                    size="sm"
                    icon={<ChartBarIcon />}
                    className="flex-1"
                  >
                    {t('plugins.actions.analytics')}
                  </Button>
                </div>
              </Card>
            ))}
          </div>
        ) : (
          <Card className="p-12 text-center">
            <CubeIcon className="mx-auto h-16 w-16 text-gray-400 mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              {searchTerm || statusFilter !== 'all' ? t('plugins.noPluginsFound') : t('plugins.noPlugins')}
            </h3>
            <p className="text-gray-600 mb-6">
              {searchTerm || statusFilter !== 'all'
                ? t('plugins.noPluginsFoundDescription')
                : t('plugins.noPluginsDescription')
              }
            </p>
            {(!searchTerm && statusFilter === 'all') && (
              <Button as={Link} to="/developer/plugins/new" icon={<PlusIcon />}>
                {t('plugins.createFirst')}
              </Button>
            )}
          </Card>
        )}

        {/* Delete Confirmation Modal */}
        <ConfirmModal
          isOpen={deleteModalOpen}
          onClose={() => setDeleteModalOpen(false)}
          onConfirm={confirmDelete}
          title={t('plugins.deletePlugin')}
          message={t('plugins.deletePluginConfirmation')}
          confirmText={t('common.delete')}
          variant="danger"
        />
      </div>
    </ErrorBoundary>
  )
}
